package com.zlyx.easy.redis.utls;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.zlyx.easy.core.annotations.SpringBean;
import com.zlyx.easy.core.utils.StringUtils;

@SpringBean(todo = { "Redis工具类" })
public class RedisUtils {

	private static StringRedisTemplate redisTemplate;

	public RedisUtils(@Autowired(required = false) StringRedisTemplate redisTemplate) {
		RedisUtils.redisTemplate = redisTemplate;
	}

	/**
	 * 获取StringRedisTemplate
	 * 
	 * @return
	 */
	public static StringRedisTemplate redisTemplate() {
		return redisTemplate;
	}

	/**
	 * 获取redis连接工厂
	 * 
	 * @return
	 */
	public static RedisConnectionFactory getConnectionFactory() {
		return redisTemplate == null ? null : redisTemplate.getConnectionFactory();
	}

	/**
	 * 删除某个key
	 * 
	 * @param key
	 * @return
	 */
	public static Boolean delete(String key) {
		return redisTemplate == null ? false : redisTemplate.delete(key);
	}

	/**
	 * 添加hash键值对
	 * 
	 * @param key
	 * @param value
	 */
	public static void set(String key, String value) {
		if (redisTemplate != null) {
			redisTemplate.opsForValue().set(key, value);
		}
	}

	/**
	 * 设置缓存
	 * 
	 * @param key
	 * @param value
	 * @param timeout
	 * @param unit
	 */
	public static void set(String key, String value, long timeout, TimeUnit unit) {
		if (redisTemplate != null) {
			redisTemplate.opsForValue().set(key, value, timeout, unit);
		}
	}

	/**
	 * 根据key得到hash值
	 * 
	 * @param key
	 * @param value
	 */
	public static String get(String key) {
		return redisTemplate == null ? null : redisTemplate.opsForValue().get(key);
	}

	/**
	 * list队列中右侧取出
	 * 
	 * @param key
	 * @return
	 */
	public static ListOperations<String, String> opsForList() {
		return redisTemplate == null ? null : redisTemplate.opsForList();
	}

	/**
	 * 推送消息(需要配合MessageListener接口来接受数据,需要手动转换数据格式)
	 * 
	 * @param channel
	 * @param message
	 */
	public static void publish(String channel, Object message) {
		if (redisTemplate != null) {
			redisTemplate.convertAndSend(channel, StringUtils.toString(message));
		}
	}

	/**
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T deserialize(byte[] bytes) {
		return redisTemplate == null ? null : (T) redisTemplate.getValueSerializer().deserialize(bytes);
	}

	/**
	 * redis是否可用
	 * 
	 * @return
	 */
	public static boolean isAvailable() {
		try {
			get("");
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
